var pageBean = null;
var dataList = {};
var cities = {};
var spaces = {};
var processPersons = {};
var currentData = null;

$(document).ready(function(e) {	
	
	$("#btnClean").click(clean);
	$("#btnBack").click(backDataList);
    $("#btnCancleContractProduct").click(backDataList);
    $("#btnCancleContractDetail").click(backDataList);

	$("#searchTimeStart111").val(getDays());
	$("#searchTimeEnd222").val(getDays());
	
	initialSpace();
	
	search(1);
	initialSpace();//加载和初始化空间信息选择
	initialPlaces();//初始化省份和市选择框
	initialSelect();
	initialProcessPerson();

});

function initialPlaces(){//加载省市数据信息
	try{
		var provinceString = localStorage.getItem('province');
		var cityString = localStorage.getItem('city');
		provinces = $.parseJSON(provinceString);
		cities = $.parseJSON(cityString);
	}catch(e){
		console.log(e.messge);
	}
}

function initialSpace(){//初始化空间信息
	try{
		var spaceString = localStorage.getItem('space');
		spaces = $.parseJSON(spaceString);
	}catch(e){
		console.log(e.messge);
	}
	$.ajax({
        url: '/euc/system/space',
        data:'',
        beforeSend: function(request) {
        	var accessToken = localStorage.getItem('accessToken');
            request.setRequestHeader("accessToken",accessToken );
        },
        dataType: 'JSON',
        async: true,
        contentType:'application/json;charset=utf-8',
        type: 'POST',
        success: function (result, textStatus, response) {
        	try{
	        	$.each(result,function(index,data){	
	        		spaces[data.id] = data;  
	   			});
	        	var spaceJson = JSON.stringify(spaces);
	        	localStorage.setItem('space',spaceJson);
        	}catch(e){
        		/*alert(e.message);*/
        	}
        },
        error: function () {
        	/*alert("error");*/
        }  
    });
}

function backDataList(){	
	$("DIV[name='dataList']").show();
	$("DIV[name='dataForm']").hide();
    $("DIV[name='contractForm']").hide();
}

function initialProcessPerson(){
	var requestJson = {functionId:'1120'};
	$.ajax({
        url: '/euc/user/functionusers',
        data:JSON.stringify(requestJson),
        beforeSend: function(request) {
        	var accessToken = localStorage.getItem('accessToken');
            request.setRequestHeader("accessToken",accessToken );
        },
        dataType: 'JSON',
        async: true,
        contentType:'application/json;charset=utf-8',
        type: 'POST',
        success: function (result, textStatus, response) {
        	var processPersonSelect = $("SELECT[name='processPerson']");
        	$.each(result,function(i,data){
        		var style = '';
        		if(data.enable == 'false' || data.enable == false){
        			style = 'style="color:red;"';
        		}
        		$('<option ' + style + ' value="'+ data.id +'">'+ data.name +'</option>').appendTo($(processPersonSelect));
        		processPersons[data.id] = data;
			});
        	$(processPersonSelect).val(0).trigger('change');
        },
        error: function () {
        	console.log("/euc/user/functionusers error");
        }  
    });
	
}

function clean(){	
	var spaceSelect = $("SELECT[name='spaceSelect']");	
	$(spaceSelect).val(0).trigger('change');
	$('input[name="searchTimeStart"]').val('');
	$('input[name="searchTimeEnd"]').val('');
}

function initialSelect(){
	var spaceSelect = $("SELECT[name='spaceSelect']");	
	$(spaceSelect).empty();
	$('<option value="0" selected="">请选择</option>').appendTo($(spaceSelect));
	$.each(spaces,function(key,space){	
   		$('<option value="'+ key +'">'+ space.spaceName +'</option>').appendTo($(spaceSelect));
	});
	$(spaceSelect).val(0).trigger('change');
}

function initialSpace(){
	try{
		var spaceString = localStorage.getItem('space');
		spaces = $.parseJSON(spaceString);
	}catch(e){
		console.log(e.messge);
	}
	$.ajax({
        url: '/euc/system/space',
        data:'',
        beforeSend: function(request) {
        	var accessToken = localStorage.getItem('accessToken');
            request.setRequestHeader("accessToken",accessToken );
        },
        dataType: 'JSON',
        async: true,
        contentType:'application/json;charset=utf-8',
        type: 'POST',
        success: function (result, textStatus, response) {
        	try{
	        	$.each(result,function(index,data){	
	        		spaces[data.id] = data;  
	   			});
	        	var spaceJson = JSON.stringify(spaces);
	        	localStorage.setItem('space',spaceJson);
        	}catch(e){
        		/*alert(e.message);*/
        	}
        },
        error: function () {
        	/*alert("error");*/
        }  
    });
}


function cancle(){
	$("DIV[name='dataList']").show();
	$("DIV[name='dataForm']").hide();
    $("DIV[name='contractForm']").hide();
}




function initailPageNumber(totalPage,currentPage,pageLength){
	try{
			var midNumber = Math.ceil((pageLength-2)/2);
			var paginList = $(".paginList");
			$(paginList).empty();			
			var prev = '<li class="paginItem"><a href="javascript:;"><span class="pagepre"></span></a></li>';
			var next = '<li class="paginItem"><a href="javascript:;"><span class="pagenxt"></span></a></li>';
			if( totalPage <= pageLength - 2){
				$(prev).appendTo($(".paginList"));
				for(var i = 1; i<totalPage+1; i++){
					var pagenItem = '<li class="paginItem"><a href="javascript:;">'+i+'</a></li>';
					if(i == currentPage){
						pagenItem = '<li class="paginItem current"><a href="javascript:;">'+i+'</a></li>';
					}			
					$(pagenItem).appendTo($(".paginList"));
				}
				$(next).appendTo($(".paginList"));
			}else{				
				if(currentPage <= midNumber){
					$(prev).appendTo($(".paginList"));
					for(var i=1;i <= pageLength - 4;i++){
						var pagenItem = '<li class="paginItem"><a href="javascript:;">'+i+'</a></li>';
						if(i == currentPage){
							pagenItem = '<li class="paginItem current"><a href="javascript:;">'+i+'</a></li>';
						}			
						$(pagenItem).appendTo($(".paginList"));
					}		
					var pagenItem = '<li class="paginItem more"><a href="javascript:;">...</a></li>';
					$(pagenItem).appendTo($(".paginList"));	
					var pagenItem = '<li class="paginItem"><a href="javascript:;">'+totalPage+'</a></li>';
					$(pagenItem).appendTo($(".paginList"));	
					$(next).appendTo($(".paginList"));
				}if(totalPage - currentPage < midNumber){

					var index = totalPage;
					for(var i=1;i <= pageLength - 4;i++){
						var pagenItem = '<li class="paginItem"><a href="javascript:;">'+index+'</a></li>';
						if(index == currentPage){
							pagenItem = '<li class="paginItem current"><a href="javascript:;">'+index+'</a></li>';
						}			
						$(pagenItem).prependTo($(".paginList"));
						index--;
					}		
					var pagenItem = '<li class="paginItem more"><a href="javascript:;">...</a></li>';
					$(pagenItem).prependTo($(".paginList"));	
					var pagenItem = '<li class="paginItem"><a href="javascript:;">'+ 1 +'</a></li>';
					$(pagenItem).prependTo($(".paginList"));
					$(prev).prependTo($(".paginList"));
					
					$(next).appendTo($(".paginList"));
				}else if(totalPage - currentPage >= midNumber && currentPage > midNumber){

					pagenItem = '<li class="paginItem current"><a href="javascript:;">'+currentPage+'</a></li>';
					$(pagenItem).prependTo($(".paginList"));
					var count = midNumber - 3;
					for(var i = 1; i<=count;i++){
						pagenItem = '<li class="paginItem"><a href="javascript:;">'+ (currentPage-i)+'</a></li>';
						$(pagenItem).prependTo($(".paginList"));
						pagenItem = '<li class="paginItem"><a href="javascript:;">'+ (currentPage+i)+'</a></li>';
						$(pagenItem).appendTo($(".paginList"));
					}
					pagenItem = '<li class="paginItem more"><a href="javascript:;">...</a></li>';
					$(pagenItem).prependTo($(".paginList"));	
					pagenItem = '<li class="paginItem"><a href="javascript:;">'+1	+'</a></li>';
					$(pagenItem).prependTo($(".paginList"));
					$(prev).prependTo($(".paginList"));
					
					pagenItem = '<li class="paginItem more"><a href="javascript:;">...</a></li>';
					$(pagenItem).appendTo($(".paginList"));	
					pagenItem = '<li class="paginItem"><a href="javascript:;">'+totalPage+'</a></li>';
					$(pagenItem).appendTo($(".paginList"));	
					$(next).appendTo($(".paginList"));
				}				
			}
			$(".paginItem").click(function(){
				if($(this).hasClass("more")){
					//alert("more");
					return;
				}else if($(this).find(".pagepre").length > 0){
					var cur = $('.paginItem.current').find("a").html();
					cur = parseInt(cur);
					if(cur > 1){
						search(cur - 1);
					}
				}else if($(this).find(".pagenxt").length > 0 ){
					var cur = $('.paginItem.current').find("a").html();
					cur = parseInt(cur);
					if(cur < totalPage){
						search(cur + 1);
					}
				}else{
					var cur = $(this).find("a").html();
					cur = parseInt(cur);
					search(cur);
				}
			});
	}catch(e){/*alert(e.messge);*/}	
}

function getSearchParameter(currentPage){
	try{
		var parameter = $("INPUT[name='parameter']").val();	
		var spaceId = $("#searchSpace").val();
		if(spaceId == '0'){
			spaceId = '';
		}		
		var searchTimeStart = $("INPUT[name='searchTimeStart']").val();
		var searchTimeEnd = $("INPUT[name='searchTimeEnd']").val();
		var requestJson = {currentPage:currentPage,data:{like:{orderName:parameter},equals:{'spaceId':spaceId,'searchTimeStart':searchTimeStart,'searchTimeEnd':searchTimeEnd}}};
		return requestJson;
	}catch(e){
		console.log(e.messge);
	}
	return false;	
}

function search(currentPage){
	var requestJson = getSearchParameter(currentPage);
	if(requestJson == false){
		console.log(2);
		return false;
	}
	console.log(JSON.stringify(requestJson));
	$.ajax({
        url: '/euc/order/queryseatorder',
        data:JSON.stringify(requestJson),
        beforeSend: function(request) {
        	var accessToken = localStorage.getItem('accessToken');
            request.setRequestHeader("accessToken",accessToken );
        },
        dataType: 'JSON',
        async: true,
        contentType:'application/json;charset=utf-8',
        type: 'POST',
        success: function (result, textStatus, response) {
        	console.log(JSON.stringify(result));
        	pageBean = result.data;
        	$("#orderTable").empty();	        	
        	$.each(result.data.list,function(i,data){

        		var bgcolor= localStorage.getItem('trcolor');
        		if(i % 2 == 0){
        			bgcolor = '';
        		}
        		var spaceName = '';
        		if($.trim(data["spaceId"]) != ''){
        			try{
        			spaceName =$.trim(spaces[data["spaceId"]].spaceName);
        			}catch(e){console.log(e.message);}
        		}        		
        		var html = '<tr '+ bgcolor +'>';
        		html += '<td>' + $.trim(data["orderNumber"]) + '</td>';
        		html += '<td>' + $.trim(data["orderName"]) + '</td>';
        		html += '<td>' + $.trim(data["orderType"]) + '</td>';
        		html += '<td>' + spaceName + '</td>';
        		html += '<td>' + $.trim(data["roomCount"]) + '</td>';
                html += '<td>' + $.trim(data["roomNames"]) + '</td>';
                html += '<td>' + $.trim(data["startTime"]) + '</td>';
        		html += '<td>' + $.trim(data["endTime"]) + '</td>';
        		html += '<td>' + $.trim(data["orderAmount"]) + '</td>';
        		html += '<td>' + $.trim(data["payAmount"]) + '</td>';
        		html += '<td>' + $.trim(data["depositAmount"]) + '</td>';
        		html += '<td style="width:170px;"><a href="javascript:detail('+data.id+');" class="tablelink">查看</a>&nbsp;&nbsp;&nbsp;</td>';
        		html += '</tr>';
	        	$("#orderTable").append(html);
	        	dataList[data.id] = data;
			});
        	$("#totalRow").html(pageBean.totalRow+'&nbsp;');
        	$("#currentPage").html(pageBean.currentPage+'&nbsp;');
        	$("#pageSize").html(pageBean.pageSize+'&nbsp;');        	
        	var pageLength = 15;
        	initailPageNumber(pageBean.totalPage,pageBean.currentPage,pageLength);        	
        },
        error: function () {
        	console.log('/euc/order/queryseatorder error');
        }  
    });
}

function setContract(order){
	try{
		var contractListTable = $("#contractListTable");
		$(contractListTable).empty();
		$.each(order.contractList,function(index,contract){			
			var html = '<tr>';
			html += '<td>'+$.trim(contract.contractType)+'</td>';
			html += '<td>'+$.trim(contract.contractAmount)+'</td>';
			html += '<td>'+$.trim(contract.roomCount)+'</td>';
			html += '<td>'+$.trim(contract.averagePrice)+'</td>';
			html += '<td>'+$.trim(contract.contractStartTime)+'</td>';
			html += '<td>'+$.trim(contract.contractEndTime)+'</td>';
			html += '<td>'+$.trim(order.salesPerson.name)+'</td>';
			html += '<td>'+$.trim(contract.createUser.name)+'</td>';
			html += '<td><a href="javascript:setContractForm('+contract.id+');" class="tablelink">查看</a></td>';
			html += '</tr>';			
			$(contractListTable).append(html);
		});
	
		
		var contractHirePurchaseListTable = $("#contractHirePurchaseListTable");		
		$(contractHirePurchaseListTable).empty();
		$.each(order.contractList,function(index,contract){	
			var rows = 1;
			try{
				if(contract.contractHirePurchaseList != null){
					rows = contract.contractHirePurchaseList.length;
				}
			}catch(e){
				console.log(e.message);
			}
			$.each(contract.contractHirePurchaseList,function(index,contractHirePurchase){
					var html = '<tr>';
					if(index == 0){
						html += '<td align="center" valign="middle" rowspan="'+rows+'">'+$.trim(contract.contractType)+'<br/>'+contract.contractStartTime +'至'+contract.contractEndTime+'</td>';	
					}					
					var hirePurchaseNumber = $.trim(contractHirePurchase.hirePurchaseNumber);
					var hirePurchaseDiscript = "";
					if(hirePurchaseNumber == '0'){
						hirePurchaseDiscript = '押金';
					}else{
						hirePurchaseDiscript = '第'+hirePurchaseNumber+'期服务费';	
					}
					html += '<td align="center" valign="middle" >'+hirePurchaseDiscript+'</td>';
					html += '<td>'+$.trim(contractHirePurchase.hirePurchaseStart)+'</td>';
					html += '<td>'+$.trim(contractHirePurchase.hirePurchaseEnd)+'</td>';
					html += '<td>'+$.trim(contractHirePurchase.bill_Date)+'</td>';
					html += '<td>'+$.trim(contractHirePurchase.hirePurchaseAmount)+'</td>';
					html += '<td>'+$.trim(contractHirePurchase.realPaymentAmount)+'</td>';
					html += '<td>'+$.trim(contractHirePurchase.hirePurchaseStatus)+'</td>';
					html += '</tr>';						
					$(contractHirePurchaseListTable).append(html);					
			});	
		});	
		
		
	}catch(e){
		console.log(e.message);	
	}	
}
var selectContractProduct = [];
function setContractProductFormTableList(contractProducts){
    if(contractProducts == null){
        return;
    }
    console.log(JSON.stringify(selectContractProduct));
    selectContractProduct =	contractProducts;
    console.log(JSON.stringify(selectContractProduct));
    var tableBody = $("#contractProductFormTable");
    var contractProductTableOfContract = $("#contractProductTableOfContract");
    $(tableBody).empty();
    $(contractProductTableOfContract).empty();
    $("input[name='contractStartTime']").attr("disabled",false);
    $("input[name='contractEndTime']").attr("disabled",false);
    var contractStartTime = "";
    var contractEndTime = "";
    $.each(contractProducts,function(index,data){
        if(contractStartTime == '' || contractStartTime > data.rentStart){
            contractStartTime = data.rentStart;
            $("input[name='contractStartTime']").val(contractStartTime);
            $("input[name='contractStartTime']").attr("disabled",true);
        }
        if(contractEndTime == ''  || contractEndTime < data.rentEnd){
            contractEndTime = data.rentEnd;
            $("input[name='contractEndTime']").val(contractEndTime);
            $("input[name='contractEndTime']").attr("disabled",true);
        }

        var html = '<tr>';
        html += '<td>工位</td>';
        html += '<td>'+data.roomName+'</td>';
        html += '<td>'+data.roomPrice+'</td>';
        html += '<td style="width:100px;"><a href="javascript:deleteSelectContractProduct('+data.roomId+');" class="tablelink">删除</a></td>';
        $(tableBody).append(html);

        var html2 = '<tr>';
        html2 += '<td>工位</td>';
        html2 += '<td>'+data.roomName+'</td>';
        html2 += '<td>'+data.roomPrice+'</td>';
        html2 += '<td>'+data.rentStart+'</td>';
        html2 += '<td>'+data.rentEnd+'</td>';
/*
        html2 += '<td style="width:100px;"><a href="javascript:deleteSelectContractProduct('+data.roomId+');" class="tablelink">删除</a></td>';
*/
        $(contractProductTableOfContract).append(html2);
    });
}
/**
 * 合同详细
 * @param contractId
 */
function setContractForm(contractId){//合同详细
    clearContractForm();
    var myContract = null;
    $.each(currentData.contractList,function(index,contractElement){
        if(contractId == contractElement.id){
            myContract = contractElement;
            return false;
        }
    });
    if(myContract == null){
        return ;
    }

    $("[contracttype][contracttype!='"+ myContract.contractType +"']").hide();
    $("[contracttype][contracttype='"+ myContract.contractType +"']").show();

    $("[formParameter='contract']").each(function(index,element){
        try{
            var name = $(element).attr("name");
            $(element).val($.trim(myContract[name]));
            if(name == 'filePath'){
                $("#reviewPDF").attr('href',myContract[name]);
                $("#reviewPDF").show();
            }
        }catch(e){
            console.log(e.messge);
        }
    });
    setContractProductFormTableList(myContract.contractProductList);
    // $("#oneOrderDetailDiv").hide();
    // $("#contractDetailDiv").show();
    $("DIV[name='dataList']").hide();
    $("DIV[name='dataForm']").hide();
    $("DIV[name='contractForm']").show();
    // $("#btnSaveContractDetail").unbind();
    // $("#btnSaveContractDetail").click(function(){
    //     updateContract(myContract);
    // });
}
function clearContractForm(){
    $("#contractProductTableOfContract").empty();
    $("[formParameter='contract']").each(function(index,element){
        try{
            $(element).val('');
        }catch(e){
            console.log(e.messge);
        }
    });
}
function detail(id){//查看订单
	try{
		currentData = dataList[id];
		console.log(JSON.stringify(currentData));
		setContract(currentData);
		if(currentData != null){
			$("DIV[name='dataList']").hide();
			$("DIV[name='dataForm']").show();
			$(window).scrollTop(0);
			var orderDetail = $("#oneOrderDetailDivContent");
			$(orderDetail).empty();
			try{//订单数据
				var spaceName = spaces[currentData.spaceId].spaceName;	
				var cityName = cities[currentData.cityId].cityName;
		    	var html = 	'<div class="incForm" >';
		    	html +=  '      <div class="formtitle ">';
		    	html +=  '            <span>订单详情</span>';
		    	html +=  '      </div>';
		    	html +=  '      <div class="formtitle-left ">';
		    	html +=  '         <ul class="forminfo">';
		    	html +=  '             <li><label >订单编号：</label><span class="iceFormInfoSpan" ">'+ currentData.orderNumber +'</span></li>';
		    	html +=  '                <li><label >订单名称：</label><span class="iceFormInfoSpan" ">'+ currentData.orderName +'</span></li>';
		    	html +=  '                <li><label >城市：</label><span class="iceFormInfoSpan" ">'+ cityName +'</span></li>';
		    	html +=  '                <li><label >当前房间总数：</label><span class="iceFormInfoSpan" ">'+ currentData.roomCount +'</span></li>';
		    	html +=  '               <li><label >已回款金额：</label><span class="iceFormInfoSpan" ">'+ currentData.payAmount +'</span></li>';
		    	html +=  '               <li><label >入驻日期：</label><span class="iceFormInfoSpan" ">'+ currentData.enterTime +'</span></li>';
		    	html +=  '               <li><label >销售日期：</label><span class="iceFormInfoSpan" ">'+ currentData.salesTime +'</span></li>';
		    	html +=  '            </ul>';
		    	html +=  '        </div>';
		    	html +=  '       <div class="formtitle-right">';
		    	html +=  '            <ul class="forminfo">';
		    	html +=  '              <li><label >客户名称：</label><span class="iceFormInfoSpan" ">'+ currentData.clientName +'</span></li>';
		    	html +=  '              <li><label >订单类型：</label><span class="iceFormInfoSpan" ">'+ currentData.orderType +'</span></li>';
		    	html +=  '              <li><label >空间：</label><span class="iceFormInfoSpan" ">'+ spaceName +'</span></li>';
		    	html +=  '              <li><label >订单总金额：</label><span class="iceFormInfoSpan" ">'+ currentData.orderAmount +'</span></li>';
		    	html +=  '              <li><label >未回款金额：</label><span class="iceFormInfoSpan" ">'+ currentData.noPayAmount +'</span></li>';
		    	html +=  '              <li><label >离场时间：</label><span class="iceFormInfoSpan" ">'+ currentData.leaveTime +'</span></li>';
		    	html +=  '              <li><label >销售人员：</label><span class="iceFormInfoSpan" ">'+ currentData.salesPerson.name +'</span></li>';
		    	html +=  '           </ul>';
		    	html +=  '       </div>';
		    	html +=  '   </div>';
					$(orderDetail).append(html);
			}catch(e){
				console.log(e.message);
			}
		}		
	}catch(e){
		console.log(e.message);
	}
}

